package com.atguigu.gulimall.cart.interceptor;

import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.cart.vo.UserInfo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @author rengang
 * @version 1.0
 * @date 2021/5/7 1:34
 */
@Component
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfo>  threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession();
        MemberRespVo loginUser = (MemberRespVo)session.getAttribute("loginUser");

//        MemberEntity memberEntity = BeanUtils.mapToBean(loginUser, MemberEntity.class);

        UserInfo userInfoTo = new UserInfo();
        if(loginUser != null){
            userInfoTo.setUserId(Long.parseLong(loginUser.getId().toString()));
        }

        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length > 0){
            for (int i = 0; i < cookies.length; i++) {
                if(CartConstant.TEMP_USER_COOKIE_NAME.equals(cookies[i].getName())){
                    userInfoTo.setUserKey(cookies[i].getValue());
                }
            }
        }
        threadLocal.set(userInfoTo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        UserInfo userInfoTo = threadLocal.get();

        if(userInfoTo.getUserKey()==null || userInfoTo.getUserKey().equals("")){
            userInfoTo.setUserKey(UUID.randomUUID().toString());
        }

        Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME,userInfoTo.getUserKey());
        cookie.setDomain("gulimall.com");
        cookie.setMaxAge(CartConstant.USER_COOKIE_TIMEOUT);

        response.addCookie(cookie);
    }


}